<?php
namespace app\common\model;

use think\Model;

/**
 * 归因追踪模型
 * 存储设备追踪信息
 */
class AttributionTrack extends Model
{
    /**
     * 数据表名
     */
    protected $table = 'gf_attribution_track';
    
    /**
     * 主键
     */
    protected $pk = 'id';
    
    /**
     * 自动时间戳
     */
    protected $autoWriteTimestamp = true;
    
    /**
     * 创建时间字段
     */
    protected $createTime = 'created_at';
    
    /**
     * 更新时间字段
     */
    protected $updateTime = false;
    
    /**
     * 字段信息
     */
    protected $schema = [
        'id' => 'int',
        'tracking_id' => 'string',
        'appkey' => 'string',
        'fingerprint' => 'string',
        'session_id' => 'string',
        'device_info' => 'json',
        'custom_params' => 'json',
        'ip_address' => 'string',
        'user_agent' => 'string',
        'expire_time' => 'datetime',
        'created_at' => 'datetime'
    ];
    
    /**
     * 获取追踪记录
     */
    public function getByTrackingId($trackingId)
    {
        return $this->where('tracking_id', $trackingId)->find();
    }
    
    /**
     * 获取设备的追踪记录
     */
    public function getByFingerprint($appkey, $fingerprint, $timeRange = null)
    {
        $query = $this->where([
            'appkey' => $appkey,
            'fingerprint' => $fingerprint
        ]);
        
        if ($timeRange) {
            $query->where('created_at', '>=', $timeRange);
        }
        
        return $query->order('created_at', 'desc')->select();
    }
    
    /**
     * 获取应用的追踪记录
     */
    public function getByAppkey($appkey, $timeRange = null, $limit = null)
    {
        $query = $this->where('appkey', $appkey);
        
        if ($timeRange) {
            $query->where('created_at', '>=', $timeRange);
        }
        
        if ($limit) {
            $query->limit($limit);
        }
        
        return $query->order('created_at', 'desc')->select();
    }
    
    /**
     * 清理过期数据
     */
    public function cleanupExpired($appkey = null)
    {
        $query = $this->where('expire_time', '<', date('Y-m-d H:i:s'));
        
        if ($appkey) {
            $query->where('appkey', $appkey);
        }
        
        return $query->delete();
    }
    
    /**
     * 获取统计信息
     */
    public function getStats($appkey, $startDate, $endDate)
    {
        return $this->where([
            'appkey' => $appkey
        ])->whereBetween('created_at', [$startDate, $endDate])
          ->field('DATE(created_at) as date, COUNT(*) as count')
          ->group('DATE(created_at)')
          ->select();
    }
}